/*
 * InputField.cpp
 *
 *  Created on: 12-12-2010
 *      Author: Przemek
 */

#include "gui/InputField.hpp"
#include "gui/UIManager.hpp"
#include "utils/GLUtils.hpp"
#include "pch.hpp"
using namespace boost;
using namespace std;

bool InputField::IntegerNumberValidator::isValid(const string& text) const
{
	try
	{
		lexical_cast<int> (text);
	}
	catch(bad_lexical_cast&)
	{
		return false;
	}

	return true;
}

bool InputField::FloatNumberValidator::isValid(const string& text) const
{
	try
	{
		lexical_cast<float> (text);
	}
	catch(bad_lexical_cast&)
	{
		return false;
	}

	return true;
}

void InputField::setManagedValidator(Validator* validator)
{
	this->validator = boost::shared_ptr<Validator>(validator);
}

void InputField::draw()
{
	UIManager::getInstance().getInputFieldBackgroundColor().setGLState();
	GLUtils::drawRectangle(Vector(0, 0), getSize());

	UIManager::getInstance().getInputFieldTextColor().setGLState();
	const GLFont& font = UIManager::getInstance().getGUIFont();
	const Dimension textBounds = font.measureTextSize(text);
	font.begin();
	const Vector& textPosition = Vector(getSize().getWidth() - textBounds.getWidth(),
			(getSize().getHeight() - textBounds.getHeight()) / 2);
	font.drawTextAt(text, textPosition);
	font.end();
}

void InputField::keyPressed(const KeyListener::EventArguments& arguments)
{
	char newCharacter = arguments.getCharacter();
	if(isValidInserCharacter(newCharacter))
	{
		string newText = text + newCharacter;

		Validator* validator = this->validator.get();
		if(validator == 0 || validator->isValid(newText))
		{
			text = newText;
		}
	}
	else if(arguments.getKey() == SDLK_BACKSPACE && text.length() > 0)
	{
		text.erase(text.length() - 1, 1);
	}
}

bool InputField::isValidInserCharacter(char character)
{
	if(isascii(character) == false)
	{
		return false;
	}
	if(isgraph(character) == false)
	{
		return (character == ' ');
	}

	return true;
}
